package com.minstone.common.util;

import java.sql.Timestamp;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.apache.log4j.Logger;

import com.minstone.common.bean.ResultBean;

/**
 * <p>
 * Title: ����ϵͳ
 * </p>
 * <p>
 * Description: �ַ��ò�����
 * </p>
 * <p>
 * Copyright: Copyright (c) 2004
 * </p>
 * <p>
 * Company: minstone
 * </p>
 * 
 * @author xwt & helay
 * @version 1.0
 */

public class StringUtil {
	private static final Logger LOGGER = Logger.getLogger(StringUtil.class);

	private StringUtil() {
	}

	/**
	 * ��ָ�����ַ�����߲����㹻λ����ַ�
	 * 
	 * @param source
	 * @param delim
	 * @return
	 */
	
	public static boolean isNull(Object obj) {
		String temp = "";
		if (obj == null)
			temp = "";
		else
			temp = obj.toString().trim();
		return temp.equals("") || temp.equals("null");
	}
	
	public static String leftLengthString(String source, int len) {
		return leftLengthString(source, len, '0');
	}
	public static void getOrderBySql(String orderDesc,String orderFile,Map<String,Object>param){
		if(!StringUtil.isBlank(param.get("orderDesc"))){
			orderDesc=" "+param.get("orderDesc").toString();
		}
		if(!StringUtil.isBlank(param.get("orderFile"))){
			orderFile=" "+param.get("orderFile").toString();
		}
		if(!StringUtil.isBlank(orderDesc)){
			param.put("orderBySql", " order by "+orderFile.replaceAll("[A-Z]", "_$0").toUpperCase()+orderDesc);
		}
	} 
	/**
	 * ��ָ�����ַ�����߲����㹻λ����ַ�
	 * 
	 * @param source
	 * @param delim
	 * @return
	 */
	public static String leftLengthString(String source, int len, char c) {
		int n = len - source.length();
		StringBuffer sChar = new StringBuffer();
		for (int i = 0; i < n; i++) {
			sChar.append(c);
		}
		return sChar.toString() + source;
	}

	public static String splitString(String str){
		String[] split = str.split(",");
		String result ="";
		for (int i = 0; i < split.length; i++) {
			if(i!=split.length-1){
				result+="'"+split[i]+"',";
			}else{
				result+="'"+split[i]+"'";
			}
		}
		return result;
	}
	
	/**
	 * ��ָ�����ַ��ָ����������
	 * 
	 * @param source
	 * @param delim
	 * @return
	 */
	public static String[] split(String source, String delim) {
		String wordLists[];
		if (source == null) {
			wordLists = new String[1];
			wordLists[0] = source;
			return wordLists;
		}
		if (delim == null)
			delim = ",";
		StringTokenizer st = new StringTokenizer(source, delim, true);
		int total = st.countTokens();
		String tempList[] = new String[total + 1];
		boolean preFlag = true;
		int j = 0;
		for (int i = 0; i < total; i++) {
			tempList[i] = st.nextToken();
			if (tempList[i].equals(delim) && preFlag) {
				tempList[i] = "";
				j++;
				if (i >= total - 1) {
					tempList[i + 1] = "";
					j++;
				}
			} else if (tempList[i].equals(delim)) {
				preFlag = true;
				if (i >= total - 1) {
					tempList[i] = "";
					j++;
				}
				total--;
				i--;
			} else {
				preFlag = false;
				j++;
			}
		}

		wordLists = new String[j];
		for (int i = 0; i < j; i++)
			wordLists[i] = tempList[i];

		return wordLists;
	}

	public static String[] split(String source, char delim) {
		return split(source, String.valueOf(delim));
	}

	public static String[] split(String source) {
		return split(source, ",");
	}

	/**
	 * ��һ�������תΪ���������(����SQL�����Ϸ�ʽ)
	 * 
	 * @param source
	 * @return
	 */
	public static String getReplaceAll(Object source) {
		if (source == null)
			return "";
		else
			return (source + "").replaceAll("'", "''");
	}
	
	public static boolean isBlank(Object obj){
		if(obj==null||obj.equals("")){
			return true;
		}
		return false;
	}

	public static String getReplaceString(String prefix, String source,
			String values[]) {
		String result = source;
		if (source == null || values == null || values.length < 1)
			return source;
		if (prefix == null)
			prefix = "%";
		for (int i = 0; i < values.length; i++) {
			String argument = prefix + Integer.toString(i + 1);
			int index = result.indexOf(argument);
			if (index != -1) {
				String temp = result.substring(0, index);
				if (i < values.length)
					temp = temp + values[i];
				else
					temp = temp + values[values.length - 1];
				temp = temp + result.substring(index + 2);
				result = temp;
			}
		}

		return result;
	}

	public static String getRepalceString(String source, String values[]) {
		return getReplaceString("%", source, values);
	}

	/**
	 * �������Ƿ��а���ָ�����ַ�
	 * 
	 * @param strings
	 * @param string
	 * @param caseSensitive
	 * @return
	 */
	public static boolean contains(String strings[], String string,
			boolean caseSensitive) {
		for (int i = 0; i < strings.length; i++)
			if (caseSensitive) {
				if (strings[i].equals(string))
					return true;
			} else if (strings[i].equalsIgnoreCase(string))
				return true;

		return false;
	}
    public static boolean isNotBank(String str){
    	if(!"".equals(str)&&str!=null){
    		return true;
    	}
    	return false;
    }

	public static boolean contains(String strings[], String string) {
		return contains(strings, string, true);
	}

	public static boolean containsIgnoreCase(String strings[], String string) {
		return contains(strings, string, false);
	}

	public static String combineStringArray(String array[], String delim) {
		int length = array.length - 1;
		if (delim == null)
			delim = "";
		StringBuffer result = new StringBuffer(length * 8);
		for (int i = 0; i < length; i++) {
			result.append(array[i]);
			result.append(delim);
		}
		result.append(array[length]);
		return result.toString();
	}

	/**
	 * ��ָ�����ַ�תΪ����
	 * 
	 * @param input
	 * @param deft
	 * @return
	 */
	public static int getInt(String input, int defValue) {
		int iRet = defValue;
		try {
			String temp = getString(input);
			if (!temp.equals("")) {
				iRet = Integer.parseInt(temp);
			}
		} catch (NumberFormatException fe) {
			LOGGER.error(fe.getMessage(), fe);
		}
		return iRet;
	}

	public static int getInt(int input, int defValue) {
		if (input == 0)
			return defValue;
		else
			return input;
	}

	public static int getInt(Object sObject) {
		int iRet = 0;
		String temp = getString(sObject, "0");
		try {
			iRet = Integer.parseInt(temp);
		} catch (NumberFormatException nfe) {
		}
		return iRet;
	}

	public static long getLong(Object sObject) {
		long lRet = 0;
		String temp = getString(sObject, "0");
		try {
			lRet = Long.parseLong(temp);
		} catch (NumberFormatException nfe) {
		}
		return lRet;
	}

	/**
	 * ���ַ��Ե�����ת����double��
	 * 
	 * @param value
	 * @return
	 */
	public static double getDouble(Object value) {
		double dRet = 0.0D;
		try {
			String temp = getString(value, "0");
			dRet = Double.parseDouble(temp);
		} catch (Exception ex) {
			LOGGER.error(ex.getMessage(), ex);
		}
		return dRet;
	}

	public static float getFloat(Object value) {
		float fRet = 0;
		try {
			String temp = getString(value, "0");
			fRet = Float.parseFloat(temp);
		} catch (Exception ex) {
			LOGGER.error(ex.getMessage(), ex);
		}
		return fRet;
	}

	/**
	 * ȡ�ô���Ĭ��ֵ���ַ�
	 * 
	 * @param obj
	 * @param deft
	 * @return
	 */
	public static String getString(Object sObject, String defStr) {
		String temp = "";
		if (sObject == null)
			temp = "";
		else
			temp = (sObject + "").trim();

		if (temp.equals("null") || temp.equals(""))
			temp = defStr;
		return temp;
	}

	public static String getString(byte[] bData) {
		if (bData == null)
			return "";
		else
			return new String(bData);
	}

	public static String getString(Object sObject) {
		return getString(sObject, "");
	}

	/**
	 * ȡ��ָ�����ȵ��ַ�
	 * 
	 * @param sObject
	 * @param length
	 * @return
	 */
	public static String getString(Object sObject, int length) {
		return getString(sObject, length, "");
	}

	/**
	 * �ַ�ת������
	 * 
	 * @param dateString
	 * @return
	 * @throws Exception
	 */
	public static Date getString2Date(String dateString) {
		SimpleDateFormat formattxt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return formattxt.parse(dateString);
		} catch (ParseException e) {
			LOGGER.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * ������ת�ַ�
	 * 
	 * @param date
	 * @return
	 * @throws Exception
	 */
	public static String getDate2String(Date date) {
		if (date == null)
			return "";
		SimpleDateFormat formattxt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return formattxt.format(date);
	}

	/**
	 * ȡ��ָ�����ȴ�Ĭ��ֵ���ַ�
	 * 
	 * @param sObject
	 * @param len
	 * @param defStr
	 * @return
	 */
	public static String getString(Object sObject, int len, String defStr) {
		String temp = "";
		if (sObject == null)
			temp = "";
		else
			temp = (sObject + "").trim();

		if (temp.equals("null") || temp.equals(""))
			temp = defStr;

		try {
			if (temp.length() > len)
				temp = temp.substring(0, len);
		} catch (StringIndexOutOfBoundsException ox) {
			LOGGER.error(ox.getMessage(), ox);
		}
		return temp;
	}

	/**
	 * ����ת����ʱ����
	 * 
	 * @param date
	 * @return
	 */
	public static java.sql.Timestamp date2Timestamp(java.util.Date date) {
		if (date == null)
			return null;
		else
			return new java.sql.Timestamp(date.getTime());
	}

	public static int length(Object object) {
		String value = object + "";
		if (value == null || value.equals(""))
			return 0;
		else
			return value.length();
	}

	/**
	 * �ѿմ�תΪָ�����ַ�
	 * 
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static String ifEmpty(Object sObject, Object defObject) {
		String temp = "";
		if (sObject == null)
			temp = "";
		else
			temp = (sObject + "").trim();

		if (temp.equals("") || temp.equals("null"))
			temp = defObject + "";

		return temp;
	}

	/**
	 * �ѿ�ֵתΪָ�����ַ�
	 * 
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static String ifNull(Object sOject, Object defObject) {
		if (sOject == null)
			return defObject + "";
		else
			return sOject + "";
	}

	public static Timestamp ifNull(Timestamp sTime, Timestamp defTime) {
		if (sTime == null)
			return defTime;
		else
			return sTime;
	}

	/**
	 * �ѻس������У��ո��תΪHTML��ʽ�ַ�
	 * 
	 * @param str
	 * @return
	 */
	public static String HTMLTurn(String value) {
		if ((null == value) || (value.trim().equals(""))) {
			return "";
		}
//		while (value.indexOf("\n") != -1) {
//			value = value.substring(0, value.indexOf("\n")) + "<br>&nbsp;"
//					+ value.substring(value.indexOf("\n") + 1);
//		}
		while (value.indexOf("</br>") != -1) {
			value = value.substring(0, value.indexOf("</br>")) + "\n"
					+ value.substring(value.indexOf("</br>") + 5);
		}
		while (value.indexOf(" ") != -1) {
			value = value.substring(0, value.indexOf(" ")) + "&nbsp;"
					+ value.substring(value.indexOf(" ") + 1);
		}
		return value;
	}

	public static String date2String(Date voteDate) {
		if (voteDate == null)
			return "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(voteDate);
	}

	/**
	 * �������ַ�תΪHTML��ʽ�ַ�
	 * 
	 * @param as_Value
	 * @return
	 * @throws Exception
	 */
	public static String htmEncode(String as_Value) {
		StringBuffer ls_Out = new StringBuffer();
		try {
			String ls_Value = as_Value;
			if (ls_Value != null) {
				for (int i = 0; i < ls_Value.length(); i++)
					ls_Out.append(emitQuote(ls_Value.charAt(i)));
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
		return ls_Out.toString();
	}

	private static String emitQuote(char c) {
		String ls_Out = null;
		try {
			if (c == '&')
				ls_Out = "&amp;";
			else if (c == '"')
				ls_Out = "&quot;";
			else if (c == '<')
				ls_Out = "&lt;";
			else if (c == '>')
				ls_Out = "&gt;";
			else
				ls_Out = String.valueOf(c);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
		return ls_Out;
	}
	
	/**
	 * �ָ��ַ�
	 * @param aSrc  Դ�ַ�
	 * @param aDelim  �ָ��
	 * @param aFieldNum �ڼ�����
	 * @return
	 */
	public static String getField(String aSrc, String aDelim, long aFieldNum) {
		if (aSrc == null)
			return null;

		int beginIndex = 0;
		int endIndex = 0;
		int fieldNum = 0;

		while (aSrc.indexOf(aDelim, endIndex) != -1) {
			endIndex = aSrc.indexOf(aDelim, endIndex);
			if (fieldNum == aFieldNum)
				break;

			++endIndex;
			beginIndex = endIndex;
			++fieldNum;
		}
		if ((beginIndex == endIndex)
				&& (((aSrc.indexOf(aDelim, 0) == -1) || (aSrc.indexOf(aDelim,
						endIndex) == -1))))
			endIndex = aSrc.length();

		if (endIndex != -1)
			return aSrc.substring(beginIndex, endIndex);

		return aSrc.substring(beginIndex);
	}

	/**
	 * ��List�����ֵתΪָ���ָ�����ַ�
	 * 
	 * @param chrList
	 * @param splitTag
	 * @return
	 */
	public static String toString(List chrList, String splitTag) {
		return toString(chrList, splitTag, true);
	}

	public static String toString(String[] chrList, String splitTag) {
		return toString(chrList, splitTag, true);
	}

	public static String toString(List chrList, String splitTag, boolean isChar) {
		String str = "";
		if (chrList != null) {
			for (int i = 0; i < chrList.size(); i++) {
				if (isChar)
					str += "'" + chrList.get(i) + "'" + splitTag;
				else
					str += chrList.get(i) + splitTag;
			}
			if (str.endsWith(splitTag))
				str = str.substring(0, str.length() - 1);
		}
		return str;
	}

	public static String toString(String[] chrList, String splitTag,
			boolean isChar) {
		String str = "";
		if (chrList != null) {
			for (int i = 0; i < chrList.length; i++) {
				if (isChar)
					str += "'" + chrList[i] + "'" + splitTag;
				else
					str += chrList[i] + splitTag;
			}
			if (str.endsWith(splitTag))
				str = str.substring(0, str.length() - 1);
		}
		return str;
	}

	/**
	 * ��ָ���ָ�����ַ�תΪList��������
	 * 
	 * @param strSet
	 * @param splitTag
	 * @return
	 */
	
	public static List toArrayList(String strSet, String splitTag) {
		List retList = new ArrayList();
		if (strSet == null)
			strSet = "";
		String[] tmp = strSet.split(splitTag);
		for (int i = 0; i < tmp.length; i++) {
			retList.add(tmp[i]);
		}
		return retList;
	}
	
	
	public static String getCode(int i,int count){
		   i = i+count;
		   NumberFormat nf = NumberFormat.getInstance();
	        //设置是否使用分组
	        nf.setGroupingUsed(false);
	        //设置最大整数位数
	        nf.setMaximumIntegerDigits(4);
	        //设置最小整数位数   
	        nf.setMinimumIntegerDigits(4);
	        //输出测试语句
	      return  nf.format(i);
	}
	
	public static String parserString(Object obj){
		if(obj==null){
			return "";
		}
		return (String) obj;
	}
	
	

	public static void main(String args[]) {
		String splitString = splitString("AS,12,11");
		System.out.println(splitString);
	}
	/****
	 * 读取数据库数据库(VARCHAR)替换换行符
	 * @param strSeparator
	 * @param repStr 替换换行代替符如br
	 * @return
	 */
	public static String strRepSepa(String strSeparator,String repStr) {

		if (isBlank(strSeparator)||isBlank(repStr))
			return "";
		return strSeparator.replaceAll("\\u000a", repStr).replaceAll("\\u000d", repStr)
				.replaceAll("/n", repStr).replaceAll("/r", repStr);
	}
	
	// 过滤特殊字符  
    public  static  String StringFilter(String   str)   throws   PatternSyntaxException   {     
                // 只允许字母和数字       
                // String   regEx  =  "[^a-zA-Z0-9]";                     
                   // 清除掉所有特殊字符  
          String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";  
          Pattern   p   =   Pattern.compile(regEx);     
          Matcher   m   =   p.matcher(str);     
          return   m.replaceAll("").trim();     
    } 
    
    
    /**
     * 将字符串数据转换成带''的类型，用于数据varchar类型的查询，例：1→'1';1,2 →'1','2';
     * @return
     */
    public static String changeParamToString(String param){
    	if (isBlank(param)) {
			return param;
		}
    	if (param.contains(",")) {
			param = param.replace(",", "','");
		}
		return "'"+param+"'";
    }
}
